package device

import (
	"device-admin/internal/app/grpc/protoc/devicec"
	"device-admin/internal/app/grpc/service/pubsub"
	"math/rand"
	"strconv"
	"sync"
	"time"

	"github.com/robfig/cron/v3"
	"google.golang.org/protobuf/proto"
)

// 设备定时任务
var (
	Cron97    = cron.New(cron.WithSeconds())
	Cron97IDs sync.Map // map[RobotID][]CronID          每个设备的设备定时器
)

func init() {
	Cron97.Start()
}

// InitCron97Cron 初始化97定时器
func Init97Cron(robotID string) {
	var crond97Task Cron97Task
	var entryIDs []cron.EntryID
	crond97Task.RobotID = robotID
	entryIDs = append(entryIDs, // 获取配置
		// 定时获取97停售状态
		func() cron.EntryID {
			r := rand.New(rand.NewSource(time.Now().UnixNano()))
			second := strconv.Itoa(r.Intn(60))
			entryID, _ := Cron97.AddFunc(second+" */2 * * * *", crond97Task.GetSaleStatus)
			return entryID
		}(),
	)
	Cron97IDs.Store(robotID, entryIDs)
}

// 97相关的定时任务
type Cron97Task struct {
	RobotID string // 设备id
}

// GetSaleStatus 获取售卖状态
func (dt *Cron97Task) GetSaleStatus() {
	saleStatusReq := &devicec.SaleStatusReq{}
	content, _ := proto.Marshal(saleStatusReq)
	pubsub.LocalMsgPublish(dt.RobotID, "97", "msg", string(saleStatusReq.ProtoReflect().Descriptor().FullName()), content, "")
}
